<template>
  <div class="chart"></div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "Chart",

  props: {
    option: {
      type: Object,
      required: true,
    },
  },

  watch: {
    option: {
      deep: true,
      handler(newValue) {
        this.chartInstance.setOption(newValue);
      },
    },
  },

  methods: {
    handleResize() {
      this.chartInstance.resize();
    },

    // 初始化实例
    initChart() {
      this.chartInstance = echarts.init(this.$el);

      window.addEventListener("resize", this.handleResize);

      // 配置
      this.chartInstance.setOption(this.option);
    },
  },

  created() {
    console.log("Chart created");
  },

  mounted() {
    console.log("Chart mounted");
    this.initChart();
  },

  beforeUnmount() {
    window.removeEventListener("resize", this.handleResize);
    // 销毁 ECharts 实例
    this.chartInstance.dispose();
  },
};
</script>

<style lang="scss" scoped>
.chart {
  width: 100%;
  height: 300px;
}
</style>
